﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
using PairingMatrix.Common.Event;
using PairingMatrix.ViewModel;

namespace PairingMatrix.View.Behavior
{
    public class DragDateStripBehavior : Behavior<DateStripControl>
    {
        private Point _mouseStartPosition;
        private bool _isMouseCaptured = false;

        protected override void OnAttached()
        {
            AssociatedObject.MouseLeftButtonDown += (sender, e) =>
            {
                _mouseStartPosition = e.GetPosition(AssociatedObject);
                AssociatedObject.CaptureMouse();
                _isMouseCaptured = true;
            };

            AssociatedObject.MouseLeftButtonUp += (sender, e) =>
            {
                AssociatedObject.ReleaseMouseCapture();
                var diff = AssociatedObject.translateTransform.X % 101;
                if (diff > 0)
                {
                    if (diff < 50)
                        AssociatedObject.translateTransform.X -= diff;
                    else
                        AssociatedObject.translateTransform.X += 101 - diff;
                }
                else
                {
                    diff = diff*-1;
                    if (diff < 50)
                        AssociatedObject.translateTransform.X += diff;
                    else
                        AssociatedObject.translateTransform.X -= 101 - diff;
                }
                _isMouseCaptured = false;
                int days = -1 * (int)(AssociatedObject.translateTransform.X / 101);
                AssociatedObject.RaiseDateSelectedEvent(days);
            };

            AssociatedObject.MouseMove += (sender, e) =>
            {
                if (_isMouseCaptured)
                {
                    var pointOnCanvas = e.GetPosition(AssociatedObject);
                    var point = new Point(pointOnCanvas.X - _mouseStartPosition.X, pointOnCanvas.Y - _mouseStartPosition.Y);

                    AssociatedObject.translateTransform.X += point.X;

                    _mouseStartPosition = pointOnCanvas;
                }
            };
        }

    }
}
